package com.study.manage.mvc.org.channel;

import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.EvaluateApplyRepository;
import com.study.manage.dal.EvaluatePriceRepository;
import com.study.manage.dal.OrderRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.EvaluateApply;
import com.study.manage.domain.EvaluatePrice;
import com.study.manage.domain.Order;
import com.study.manage.domain.User;
import com.study.manage.domain.enumm.EAState;
import com.study.manage.domain.enumm.EvaluateVerify;
import com.study.manage.domain.enumm.ItemType;
import com.study.manage.dto.JsonResponseBean;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.BaseController;
import com.study.manage.mvc.common.CommonService;
import com.study.manage.utils.CmnDateUtil;
import com.study.manage.utils.DateTimeUtil;
import com.study.manage.utils.MapUtils;

@Controller
@RequestMapping("org/checkInformation")
public class CheckEvaluateInfoController extends BaseController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private EvaluatePriceRepository evaluatePriceRepository;
    @Autowired
    private EvaluateApplyRepository evaluateApplyRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CheckEvaluateInfoService service;
    @Autowired
    private CommonService commonService;

    @RequestMapping(path = "info", method = RequestMethod.GET)
    public String info(Long id,ModelMap model) {
    	
    	SessionUser su = (SessionUser) session.getAttribute("user");
    	Map<String, Object> map = service.getBaseData(id,su.getId());
    	model.put("number",map);
        return "org/evaluate/checkInformation";
    }

    @ResponseBody
    @RequestMapping(path = "getData", method = RequestMethod.GET)
    public JsonResponseBean getData(Long evaluateId,Integer flg,
    		 String name, EvaluateVerify verify, EAState state,
    		 @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
             @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt,
             @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
    	
    	List<Long> evaluateIds = new ArrayList<>(Arrays.asList(evaluateId));
    	Map<String,Date> timeMap = commonService.getTimes(beginAt,endAt,evaluateIds,flg);
        beginAt = timeMap.get("beginAt");
        endAt = timeMap.get("endAt");
    	session.setAttribute("beginAt",beginAt);
        session.setAttribute("endAt",endAt);
        SessionUser su = (SessionUser) session.getAttribute("user");
        Page<EvaluateApply> page = evaluateApplyRepository.findEvaluateApplys(evaluateId,beginAt,endAt, name, verify, state,su.getId(), pageable);
    	Object obj = page.map(new Converter<EvaluateApply, Map<String, Object>>() {
    		@Override
    		public Map<String, Object> convert(EvaluateApply source) {
    			Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.userId);
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                map.put("userPhone", user.phone == null ? "--" : user.phone);
                if(source.verify!=null) map.put("verifyDesc", source.verify.desc);
                map.put("stateDesc", source.state.desc);
                if (source.referenceId != null) {
                    User refUer = userRepository.findOne(source.referenceId);
                    map.put("refName", refUer.name);
                }else {
                	map.put("refName", "--");
                }
                if (source.evaluatePriceId != null) {
                    EvaluatePrice ep = evaluatePriceRepository.findOne(source.evaluatePriceId);
                    map.put("epName", ep.title + "(" + ep.charge + ")");
                }else {
                	map.put("epName", "--");
                }
                Order order = orderRepository.findByItemTypeAndItemIdAndUserId(ItemType.EvaluateSignup, source.evaluateId, source.userId);
                if (order != null) {
                    map.put("orderItemPrice", order.itemPrice);
                }else {
                	map.put("orderItemPrice", "--");
                }
                return map;
		      }
		  });
        return new JsonResponseBean(obj,true);
    }

    @ResponseBody
    @RequestMapping(path = "getEchartsDatas", method = RequestMethod.GET)
    public JsonResponseBean info_detail_count_detail( Integer  flg,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt, Long id) {
    	
        List<Long> evaluateIds = new ArrayList<>(Arrays.asList(id));
        Map<String,Date> timeMap = commonService.getTimes(beginAt,endAt,evaluateIds,flg);
        beginAt = timeMap.get("beginAt");
        endAt = timeMap.get("endAt");
        SessionUser su = (SessionUser) session.getAttribute("user");
        List<Object[]> objs = evaluateApplyRepository.countByEvaluateId(beginAt, endAt, evaluateIds,su.getId());
        List<Map<String, Object>> list = service.getReturnList(beginAt,endAt,objs);
        return new JsonResponseBean(list,true);
    }

    @RequestMapping(path = "exportExecl", method = RequestMethod.GET)
    public void exportExecl(Long id,HttpServletResponse response) throws Exception {

    	Date beginAt = (Date) session.getAttribute("beginAt");
    	Date endAt = (Date) session.getAttribute("endAt");
    	SessionUser su = (SessionUser) session.getAttribute("user");
    	List<EvaluateApply> list = evaluateApplyRepository.findEvaluateApplys(id,beginAt,endAt,null,su.getId());
    	StringBuilder context = new StringBuilder("报名时间,参赛编号,用户(ID),电话,渠道,报名状态,付款状态,票种,付款\n");
    	for(EvaluateApply source : list) {
    		User user = userRepository.findOne(source.userId);
    		String refName = "";
    		String epName= "";
    		String itemPrice= "";
    		String sourceVerifyDesc = "";
    		if (source.referenceId != null) {
                User refUer = userRepository.findOne(source.referenceId);
                refName = refUer.name;
            };
            if(source.verify!=null) {
            	sourceVerifyDesc = source.verify.desc;
            } 
            if (source.evaluatePriceId != null) {
                EvaluatePrice ep = evaluatePriceRepository.findOne(source.evaluatePriceId);
                epName = ep.title + "(" + ep.charge + ")";
            }
            Order order = orderRepository.findByItemTypeAndItemIdAndUserId(ItemType.EvaluateSignup, source.evaluateId, source.userId);
            if (order != null) {
            	itemPrice = order.itemPrice;
            }
            context.append(CmnDateUtil.formatDate(source.createdAt.toString())).append(",")
		            .append(source.id).append(",")
		            .append(user.name+"("+user.number+")").append(",")
		            .append(user.phone==null ? "" : user.phone).append(",")
		            .append(refName).append(",")
		            .append(sourceVerifyDesc).append(",")
		            .append(source.state.desc).append(",")
		            .append(epName).append(",")
		            .append(itemPrice).append("\n");
    	};
        String nowDate = "渠道("+DateTimeUtil.getYYmmDD(beginAt)+"-"+DateTimeUtil.getYYmmDD(endAt)+").csv";
        String fileName = new String(nowDate.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
        OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
        // 要输出的内容
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        osw.write(new String(new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
        osw.write(context.toString());
        osw.flush();
    }
    
    
}
